<template>
  <div>
    <el-form
      ref="dataFormRef"
      v-loading="loading"
      :model="state.form"
      :rules="dataRules"
      label-width="200px"
      label-position="top"
      :disabled="operType === 'view'"
    >
      <el-row :gutter="24">
        <el-col :span="12" class="mb20">
          <el-form-item label="流程名称" prop="defFlowId">
            <el-input
              v-model="state.form.flowName"
              placeholder="流程名称"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="流程实例" prop="flowInstId">
            <el-input
              v-model="state.form.flowInstId"
              placeholder="流程实例ID"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="目标节点" prop="toRunNodeId" required>
            <CommonSelect
              v-model:defaultValue="state.form.toRunNodeId"
              :placeholder="translate('请选择驳回目标节点')"
              label="nodeName"
              value="id"
              :url="rejectNodeListUrl"
              :query-params="state.nodeParams"
              auto-query
              @change="handleToRunNodeChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="目标节点办理人" prop="handleUserId">
            <el-tooltip placement="top">
              <template #content>
                注：【目标节点办理人】为空时会驳回给目标节点的默认办理人,当【目标节点办理人】不为空时，则会驳回给指定的办理人员
              </template>
              <CommonSelect
                ref="handleUserIdRef"
                v-model:defaultValue="state.form.handleUserId"
                :placeholder="translate('请选择目标节点办理人')"
                expanding
                label="userName"
                value="id"
                :url="nodeUserListUrl"
                auto-query
                @loaded="handleUserLoaded"
              />
            </el-tooltip>
            <div style="margin-left: 10px; padding-left: 10px">
              <el-button type="primary" @click="showUserPicker"
                >其它人员</el-button
              >
              {{ state.form.handleUserName }}
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <footer class="el-dialog__footer">
      <span class="dialog-footer">
        <el-button type="warning" icon="circle-close" @click="handleClose"
          >取消</el-button
        >
        <el-button
          type="primary"
          :loading="loading"
          :disabled="state.confirmDisable"
          @click="handleUpdate"
        >
          确认
        </el-button>
      </span>
    </footer>
    <StaffPicker ref="staffPickerRef" @change="handleStaffConfirm" />
  </div>
</template>

<script setup lang="ts" name="RunRejectForm">
import { translate } from "@/plugins/i18n";
import { useMessage } from "@/hooks/message";
import CommonSelect from "@/components/commonSelect.vue";
import StaffPicker from "@/components/staffPicker.vue";
import { onMounted, reactive, ref, watch } from "vue";
import * as doJob from "@/api/flow/task/index";

const $message = useMessage();
const $emit = defineEmits(["confirm", "closed"]);
// 定义变量内容
const dataFormRef = ref();
const loading = ref(false);
const operType = ref("");
const handleUserIdRef = ref(null);
const staffPickerRef = ref(null);

const props = defineProps({
  currJob: {
    type: Object,
    default: null
  },
  comment: {
    type: String,
    default: null
  }
});

// 提交表单数据
const state = reactive({
  confirmDisable: true,
  form: {
    defFlowId: "",
    flowName: "",
    flowInstId: "",
    toRunNodeId: "",
    handleUserId: "",
    handleUserName: "",
    nodeType: ""
  },
  nodeParams: {
    runNodeId: props.currJob.runNodeId
  }
});

// 定义校验规则
const dataRules = ref({
  defFlowId: [{ required: true, message: "流程名称不能为空", trigger: "blur" }],
  flowInstId: [
    { required: true, message: "流程实例ID不能为空", trigger: "blur" }
  ],
  toRunNodeId: [
    { required: true, message: "达到节点名称不能为空", trigger: "blur" }
  ]
});

const handleUserLoaded = () => {
  nextTick(() => {
    const opt = handleUserIdRef.value.getOptions();
    if (opt && opt.length > 0) {
      state.confirmDisable = false;
    } else {
      state.confirmDisable = true;
    }
  });
};

const rejectNodeListUrl = computed(() => {
  return `/esflow/run/node/pre/${props.currJob.flowInstId}`;
});

const nodeUserListUrl = computed(() => {
  return `/esflow/run/job/list/user/${state.form.toRunNodeId}`;
});

const handleToRunNodeChange = (id, node) => {
  state.form.toRunNodeId = id;
  state.form.nodeType = node.nodeType;
};

function initJobData() {
  Object.assign(state.form, props.currJob);
  state.form.flowInstId = props.currJob.flowInstId;
  state.form.defFlowId = props.currJob.defFlowId;
  if (props.currJob.runFlow) {
    state.form.flowName = props.currJob.runFlow.flowName;
  }
}

const showUserPicker = () => {
  staffPickerRef.value.show();
};

const handleStaffConfirm = rows => {
  state.form.handleUserId = rows[0].id;
  state.form.handleUserName = rows[0].userName;
};

const handleClose = () => {
  $emit("closed");
};

async function handleUpdate() {
  dataFormRef.value.validate(async valid => {
    if (valid) {
      loading.value = true;
      try {
        const params = {
          id: props.currJob.id,
          toRunNodeId: state.form.toRunNodeId,
          handleUserId: state.form.handleUserId,
          nodeType: state.form.nodeType,
          comment: props.comment
        };
        doJob.reject(params).then(res => {
          if (res.code === 200) {
            useMessage().success("驳回成功");
            $emit("confirm");
            setTimeout(() => {
              // 异步异常
              loading.value = false;
            }, 3000);
          } else {
            useMessage().error(res.msg);
          }
        });
      } catch (e) {
        loading.value = false;
      }
    }
  });
}

// 监听双向绑定
watch(
  () => props.currJob.id,
  val => {
    initJobData();
  }
);

onMounted(() => {
  initJobData();
});
</script>

<style lang="scss" scoped>
.el-dialog__footer {
  text-align: center;

  .dialog-footer {
    text-align: center;
  }
}
</style>
